<template>
  <div>
    <el-form :inline="true" size="small" class="filter-form" @submit.native.prevent>
      <el-form-item label="一级科室">
        <el-select v-model="filters.level1" placeholder="请选择" style="width: 120px" clearable @change="debouncedFetchData">
          <el-option v-for="item in level1Options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="二级科室">
        <el-select v-model="filters.level2" placeholder="请选择" style="width: 120px" :disabled="!filters.level1" clearable @change="debouncedFetchData">
          <el-option v-for="item in level2Options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="药房">
        <el-select v-model="filters.pharmacy" placeholder="请选择" style="width: 120px" clearable @change="debouncedFetchData">
          <el-option v-for="item in pharmacyOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="filters.status" placeholder="请选择" style="width: 120px" clearable @change="debouncedFetchData">
          <el-option label="启用" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="filters.dateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
                        end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 240px" clearable @change="debouncedFetchData" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">查询</el-button>
        <el-button type="primary" @click="handleAdd" plain>+新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%; margin-top: 16px" row-key="id"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" border>
      <el-table-column prop="name" label="科室" min-width="120" />
      <el-table-column prop="level" label="类型" min-width="80" />
      <el-table-column prop="pharmacy" label="配置药房" min-width="120" />
      <el-table-column prop="remark" label="备注" min-width="120" />
      <el-table-column prop="status" label="状态" min-width="80">
        <template slot-scope="scope">
          <span
              :class="scope.row.status === '1' || scope.row.status === 1 ? 'status-enabled' : 'status-disabled'"
          >
            {{ scope.row.status === '1' || scope.row.status === 1 ? '启用' : '停用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="120">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" style="color: red" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 16px 0; text-align: right;">
      <el-pagination background layout="prev, pager, next, sizes, jumper, total" :total="total" :page-size="pageSize"
                     :current-page="page" @current-change="handlePageChange" @size-change="handleSizeChange"
                     :page-sizes="[10, 20, 50, 100]" />
    </div>

    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="500px"
        @close="resetDialog"
    >
      <el-form :model="dialogForm" label-width="80px">
        <el-form-item label="一级科室">
          <el-select v-model="dialogForm.level1" placeholder="请选择" @change="onDialogLevel1Change">
            <el-option v-for="item in level1Options" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="二级科室">
          <el-select v-model="dialogForm.level2" placeholder="请选择" :disabled="!dialogForm.level1">
            <el-option v-for="item in dialogLevel2Options" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="药房">
          <el-select v-model="dialogForm.pharmacy" placeholder="请选择">
            <el-option v-for="item in pharmacyOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="dialogForm.status">
            <el-radio :label="'1'">启用</el-radio>
            <el-radio :label="'0'">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="dialogForm.remark"/>
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align:right;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDialog">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { debounce } from 'lodash'

// 页面名称：科室药房配置页面
export default {
  name: 'PharmacyDrugConfig',
  data() {
    return {
      filters: {
        level1: '',
        level2: '',
        pharmacy: '',
        status: '',
        dateRange: [],
        parentId: null
      },
      allDepartments: [],
      level1Options: [],
      level2Options: [],
      pharmacyOptions: [],
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: '新增/编辑',
      dialogMode: 'add',
      dialogForm: {
        id: '',
        level1: '',
        level2: '',
        pharmacy: '',
        status: '',
        remark: ''
      },
      dialogLevel2Options: [],
      debouncedFetchData: null
    }
  },
  methods: {
    async fetchData() {
      const params = {
        page: this.page,
        pageSize: this.pageSize,
      }
      if (this.filters.level2) {
        params.name = this.filters.level2
        params.level = '二级'
      } else if (this.filters.level1) {
        params.name = this.filters.level1
        params.level = '一级'
      }
      if (this.filters.pharmacy) params.pharmacy = this.filters.pharmacy
      if (this.filters.status) params.status = this.filters.status
      if (this.filters.dateRange && this.filters.dateRange.length === 2) {
        if (this.filters.dateRange[0]) params.startDate = this.filters.dateRange[0]
        if (this.filters.dateRange[1]) params.endDate = this.filters.dateRange[1]
      }

      const level1Obj = this.level1Options.find(item => item.value === this.filters.level1)
      const level2Obj = this.level2Options.find(item => item.value === this.filters.level2)
      params.name = level2Obj ? level2Obj.label : (level1Obj ? level1Obj.label : undefined)
      params.level = level2Obj ? '二级' : (level1Obj ? '一级' : undefined)

      const { data } = await axios.get('/departmentPharmacyConfig/list', { params })
      this.tableData = this.formatTree(data.data)
      this.total = data.total
    },
    formatTree(list) {
      // 假设后端返回的有 parentId 字段
      const map = {}
      list.forEach(item => { map[item.id] = { ...item, children: [] } })
      const tree = []
      list.forEach(item => {
        if (item.parentId && map[item.parentId]) {
          map[item.parentId].children.push(map[item.id])
        } else {
          tree.push(map[item.id])
        }
      })
      return tree
    },
    handlePageChange(val) {
      this.page = val
      this.fetchData()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.fetchData()
    },
    async handleEdit(row) {
      this.dialogTitle = '编辑'
      this.dialogMode = 'edit'
      this.dialogVisible = true

      // 直接用 row.id 作为当前编辑项的 id
      let level2 = null, level1 = null
      if (row.level === '二级') {
        level2 = this.allDepartments.find(item => item.id === row.id)
        level1 = this.allDepartments.find(item => item.id === (level2 ? level2.parentId : null))
      } else {
        level1 = this.allDepartments.find(item => item.id === row.id)
      }

      this.dialogForm = {
        id: row.id, // 关键：存id
        level1: level1 ? level1.id : '',
        level2: level2 ? level2.id : '',
        pharmacy: row.pharmacy,
        status: row.status,
        remark: row.remark
      }
      this.updateDialogLevel2Options()
    },
    handleDelete(row) {
      this.$confirm('确定要删除该配置吗？', '提示', { type: 'warning' })
          .then(async () => {
            await axios.post(`/departmentPharmacyConfig/delete/${row.id}`)
            this.$message.success('删除成功')
            this.fetchData()
          })
    },
    async handleAdd() {
      this.dialogTitle = '新增'
      this.dialogMode = 'add'
      this.dialogVisible = true
      this.resetDialog()
    },
    async getConfigById(id) {
      const { data } = await axios.get(`/departmentPharmacyConfig/${id}`)
      // data 就是单条 DepartmentPharmacyConfig
    },
    // 获取所有科室
    async fetchAllDepartments() {
      const { data } = await axios.get('/departmentPharmacyConfig/list', {
        params: { page: 1, pageSize: 1000 }
      })
      this.allDepartments = data.data
      // 一级科室
      this.level1Options = this.allDepartments
          .filter(item => item.parentId === 0)
          .map(item => ({ label: item.name, value: item.id }))
    },
    // 监听一级科室变化，自动加载二级科室
    updateLevel2Options() {
      this.filters.level2 = ''
      this.level2Options = this.allDepartments
          .filter(item => item.parentId === this.filters.level1)
          .map(item => ({ label: item.name, value: item.id }))
    },
    onDialogLevel1Change() {
      this.dialogForm.level2 = ''
      this.updateDialogLevel2Options()
    },
    updateDialogLevel2Options() {
      this.dialogLevel2Options = this.allDepartments
          .filter(item => item.parentId === this.dialogForm.level1)
          .map(item => ({ label: item.name, value: item.id }))
    },
    async submitDialog() {
      if (!this.dialogForm.level1) return this.$message.warning('请选择一级科室')
      let config = {
        id: this.dialogForm.id,
        parentId: this.dialogForm.level2 ? this.dialogForm.level1 : 0,
        name: '',
        level: '',
        pharmacy: this.dialogForm.pharmacy,
        status: this.dialogForm.status,
        remark: this.dialogForm.remark
      }
      if (this.dialogForm.level2) {
        const level2Obj = this.allDepartments.find(item => item.id === this.dialogForm.level2)
        config.name = level2Obj ? level2Obj.name : ''
        config.level = '二级'
        config.parentId = this.dialogForm.level1
      } else {
        const level1Obj = this.allDepartments.find(item => item.id === this.dialogForm.level1)
        config.name = level1Obj ? level1Obj.name : ''
        config.level = '一级'
        config.parentId = 0
      }
      if (this.dialogMode === 'add') {
        delete config.id
        await axios.post('/departmentPharmacyConfig/add', config)
        this.$message.success('新增成功')
      } else {
        await axios.post('/departmentPharmacyConfig/edit', config)
        this.$message.success('编辑成功')
      }
      this.dialogVisible = false
      this.fetchAllDepartments()
      this.fetchData()
    },
    async deleteDialog() {
      const level2Obj = this.allDepartments.find(item => item.id === this.dialogForm.level2)
      const level1Obj = this.allDepartments.find(item => item.id === this.dialogForm.level1)
      let id = level2Obj ? level2Obj.id : (level1Obj ? level1Obj.id : null)
      if (!id) return
      await axios.post(`/departmentPharmacyConfig/delete/${id}`)
      this.$message.success('删除成功')
      this.dialogVisible = false
      this.fetchAllDepartments()
      this.fetchData()
    },
    resetDialog() {
      this.dialogForm = {
        id: '',
        level1: '',
        level2: '',
        pharmacy: '',
        status: '',
        remark: ''
      }
      this.dialogLevel2Options = []
    },
    statusFormatter(row) {
      return row.status === '1' || row.status === 1 ? '启用' : '停用'
    },
    // 获取药房下拉
    async fetchPharmacyOptions() {
      const { data } = await axios.get('/pharmacies/list')
      // data.records 是药房数组
      this.pharmacyOptions = (data.records || []).map(item => ({
        label: item.pharmacyName,
        value: item.pharmacyName
      }))
    },
    formatDateTime(val) {
      if (!val) return ''
      // 兼容字符串和Date对象
      const date = new Date(val)
      if (isNaN(date.getTime())) return val
      const y = date.getFullYear()
      const m = ('0' + (date.getMonth() + 1)).slice(-2)
      const d = ('0' + date.getDate()).slice(-2)
      const h = ('0' + date.getHours()).slice(-2)
      const min = ('0' + date.getMinutes()).slice(-2)
      const s = ('0' + date.getSeconds()).slice(-2)
      return `${y}-${m}-${d} ${h}:${min}:${s}`
    }
  },
  watch: {
    'filters.level1': function (val) {
      this.updateLevel2Options()
    },
    'dialogForm.level1': function (val) {
      this.updateDialogLevel2Options()
    }
  },
  created() {
    this.debouncedFetchData = debounce(() => {
      this.page = 1
      this.fetchData()
    }, 400)
    this.fetchAllDepartments()
    this.fetchPharmacyOptions()
    this.fetchData()
  }
}
</script>

<style scoped>
.filter-form {
  margin-bottom: 16px;
}
.status-enabled {
  color: #52c41a; /* 浅绿色 */
  font-weight: bold;
}
.status-disabled {
  color: #ff7875; /* 浅红色 */
  font-weight: bold;
}
</style>